package br.com.felinelayer.common;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Vanius Roberto Bittencourt
 */
public class FelLogger {

    private static File fileIni = new File( "../../felineLayerLogDef.ini" );
    private static File fileLog = new File( "../../felineLayerLogDef.log" );
    private static long lastDateTme = 0;
    private static ArrayList<String> include = new ArrayList<>();
    private static ArrayList<String> exclude = new ArrayList<>();

    private static void loadConfiguration() throws FileNotFoundException, IOException {
        if ( !fileIni.exists() ) {
            return;
        }
        if ( (lastDateTme == 0) || (lastDateTme < fileIni.lastModified()) ) {
            Properties pro = new Properties();
            pro.load( new FileInputStream( fileIni ) );
            include.clear();
            include.addAll( Arrays.asList( pro.getProperty( "include" ).split( ";" ) ) );
            exclude.clear();
            exclude.addAll( Arrays.asList( pro.getProperty( "exclude" ).split( ";" ) ) );
            lastDateTme = fileIni.lastModified();
        }
    }

    private static void append( String texto ) {
        try {
            FileOutputStream appendedFile = new FileOutputStream( fileLog, true );
            appendedFile.write( texto.getBytes() );
        } catch ( IOException ex ) {
            Logger.getLogger( FelLogger.class.getName() ).log( Level.SEVERE, null, ex );
        }
    }

    public static synchronized void log( String texto ) {
        try {
            boolean b = false;
            loadConfiguration();
            for ( String s : include ) {
                if ( s.equals( "*" ) || texto.indexOf( s ) > 0 ) {
                    b = true;
                }
            }
            for ( String s : exclude ) {
                if ( s.equals( "*" ) || texto.indexOf( s ) > 0 ) {
                    b = false;
                }
            }
            if ( include.isEmpty() && exclude.isEmpty() ) {
                b = true;
            }
            if ( b ) {
                System.out.println( texto );
                append( texto );
            }
        } catch ( IOException ex ) {
            Logger.getLogger( FelLogger.class.getName() ).log( Level.SEVERE, null, ex );
        }
    }
}
